package com.rongshu.view.web;

import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.FileUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.submitArticle.activity.SubmitArticleActivity;
import com.utils.SPUtils;
import com.utils.constants.SPKey;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by zhengweis on 2018/12/29.
 * description：加载本地得html页面
 */
public class LocalWebActivity extends BaseActivity {
    @BindView(R.id.content)
    WebView content;
    @BindView(R.id.head_left)
    RelativeLayout headLeft;
    @BindView(R.id.head_middle)
    TextView headMiddle;
    @BindView(R.id.head_right)
    RelativeLayout headRight;
    @BindView(R.id.know)
    TextView know;
    private String data;
    private boolean skinState = false;
    private String fontColor = "color : #2c2c2c";
    String title;
    String url;

    @Override
    protected int initLayout() {
        return R.layout.activity_submit_article_protocol;
    }

    @Override
    protected void initView() {
        Intent inEntry = getIntent();
        if (inEntry != null) {
            //获取意图数据
            url = getIntent().getStringExtra(Constant.INTENT_H5);
            title = getIntent().getStringExtra(Constant.INTENT_TITLE);
        }
        headMiddle.setText(title);
        if (TextUtils.equals(title, "投稿须知")) {
            headLeft.setVisibility(View.GONE);
            headRight.setVisibility(View.VISIBLE);
            know.setVisibility(View.VISIBLE);
        } else {
            headLeft.setVisibility(View.VISIBLE);
            headRight.setVisibility(View.GONE);
            know.setVisibility(View.GONE);
        }

        WebSettings settings = content.getSettings();
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setBlockNetworkImage(false);
        settings.setUseWideViewPort(true);
        settings.setBuiltInZoomControls(false);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setSupportMultipleWindows(true);
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(false);
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setGeolocationEnabled(true);
        // 开启定位
        settings.setDomStorageEnabled(true);
        content.addJavascriptInterface(new JavaScriptObject(this), "app");
        content.loadUrl("file:///android_asset/" + url);

//        WebSettings settings = content.getSettings();
//        settings.setTextZoom(300);
//        content.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
//        settings.setDefaultTextEncodingName("UTF-8");
//        readFile();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    protected void onDestroy() {
        if (content != null) {
            ViewGroup parent = (ViewGroup) content.getParent();
            if (parent != null) {
                parent.removeView(content);
            }
            content.clearCache(true);
            content.removeAllViews();
            content.pauseTimers();
            content.destroy();
        }
        super.onDestroy();
    }

    @OnClick({R.id.head_left, R.id.head_right, R.id.know})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_left:
            case R.id.head_right:
                finish();
                break;
            case R.id.know:
                if (TextUtils.equals(url, Common.SUBMIT_ARTICLE_NOTICE)) {
                    SPUtils.putPreferences(SPKey.AGERR_AGREEMENT, true);
                }
                Intent intent = new Intent(this, SubmitArticleActivity.class);
                startActivity(intent);
                finish();
                break;
        }
    }

    public void readFile() {
        skinState = SPUtils.getPreferences(SPKey.SKIN_STATE, false);
        fontColor = skinState ? "color : #a8a8a8" : "color : #2c2c2c";
        try {
            //字节读流
            InputStream in = getAssets().open(url);
            //字节与字符的桥梁
            InputStreamReader ir = new InputStreamReader(in, "utf-8");
            //字符读流
            BufferedReader br = new BufferedReader(ir);
            //创建文件夹
            File file = new File(FileUtils.initPath());
            if (!file.exists()) {
                file.mkdirs();
            }
            //创建文件
            String filename = FileUtils.initPath() + "htmlTxt.html";
            File files = new File(filename);
            if (files.exists()) {
                files.delete();
            }
            files.createNewFile();
            //缓存写的数据
            StringBuffer sbffer = new StringBuffer();
            //写入本地
            FileWriter write = new FileWriter(files);
            //字符写流
            BufferedWriter bw = new BufferedWriter(write);
            String line = null;
            while ((line = br.readLine()) != null) {
                sbffer.append(line);
            }
            bw.write(sbffer.toString());
            bw.close();
            br.close();
            data = sbffer.toString().replace("color : #2c2c2c", fontColor);
            content.loadDataWithBaseURL("", data, "text/html", "utf-8", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
